import React, { useEffect, useState } from 'react'
import './index.scss'
import { connect } from 'react-redux'
import cart_enpty from './img/cart-empty-2.png'
import store_red from './img/store-red.png'
import gift from './img/gift.png'
import { editCartAction, incrementNum, decrementNum } from '../../store/action/cart';
import { Badge } from 'antd-mobile'
//引入 接口
import { preOrder } from '../../api/order'
//发布订阅
// import PubSub from 'pubsub-js'
const Cart = (props) => {
    //结算，将选中的每种商品的cartId 放在同一个数组中，再调用 生成预订单的接口
    const [num, setNum] = useState(0)
    const [sum, setSum] = useState(0)

    useEffect(() => {
        getSum();
    })
    const jiesuanFn = () => {
        const list = props.cart;
        let cartId = [];//选中的商品的cartId
        let cartList = [];//选中的商品的数组
        list.forEach(item => {
            if (item.checked) {
                cartId.push(item.cartId);
                cartList.push(item);
            }
        });
        //调用 生成预订单的接口
        preOrder({
            cartId: cartId,
            totalMoney: sum
        }).then(res => {
            if (res.data.code === 666) {
                //跳转页面
                props.history.push({
                    pathname: "/ordersubmit", state: { cartList, preOrderId: res.data.result.preOrderId, sum: sum }
                });
            }
        })
        // PubSub.publish('numAll', num)

    }
    const changeCK = (id, ev) => {
        let list = props.cart.map(item => {
            if (item.id === id) {
                item.checked = ev.target.checked
            }
            return item

        })
        props.editCartAction(list)
        getSum();
    }
    const checkedAll = (e) => {
        let list = props.cart.map(item => {

            item.checked = e.target.checked

            return item

        })
        getSum();
        props.editCartAction(list)
    }
    //计算总数量和总价格
    const getSum = () => {
        let sum = 0;
        let num = 0;
        let data = [...props.cart];
        data.filter(v => {
            if (v.checked) {//选中状态，需要计算总价格
                sum += v.price * v.num;
                num += v.num;
            }
            return { sum, num }
        })
        console.log(sum);
        // this.setState({ sum: sum, num: num })
        setNum(num)
        setSum(sum)
    }
    const addNum = (id) => {
        console.log(id);
        props.incrementNum(id);
        getSum();
    }
    const delNum = (id) => {
        console.log(id);
        props.decrementNum(id);
        getSum();

    }
    const { cart } = props;
    return (
        <div>
            {
                num === 0 ? '' :
                    <Badge content={num}>

                    </Badge>
            }
            {
                cart.length === 0 ? <div style={{ margin: '200px 100px' }}>
                    <img src={cart_enpty} alt={cart_enpty} style={{ width: '100%' }} />
                    <p style={{ fontSize: '14px', fontWeight: '600' }}>零食告急！购物车是空的哦</p>
                </div>
                    :
                    < div className='cart_ta' >
                        {/* 头部 */}
                        < div className='cart_top' >
                            <div className='postage-less'>
                                再购买
                                <span className='remain-count'>¥61</span>
                                免邮费
                            </div>
                            <button className='more'>去凑单</button>
                            <span style={{ color: '#fc556c', fontSize: '16px', marginLeft: '25px' }}>编辑</span>
                        </div >
                        {/* 领券 */}
                        <div className='GiftWrap'>
                            <div className='GiftWrap_left'>
                                <img src={store_red} alt={store_red} />
                                <span>旺仔旺铺</span>
                            </div>
                            <div style={{ color: '#f12525', lineHeight: '42px', position: 'absolute', right: '15px' }}>领券</div>
                        </div>
                        {/* 满赠 */}
                        <div className='GiftWrap_2'>
                            <div className='GiftWrap_left_2'>
                                <img src={gift} alt={gift} />
                                <span style={{ color: '#343434', lineHeight: '42px', fontSize: '12px', fontWeight: '600' }}>已满299元下单可获赠品1件</span>
                            </div>
                            <div style={{ color: '#999', lineHeight: '42px', position: 'absolute', right: '15px', fontSize: '12px' }}>查看活动</div>
                        </div>
                        <div className='pic_gift'>
                            <div className='pic_bg'></div>
                        </div>
                        {/* 商品 */}
                        <ul className='things_box'>
                            {
                                cart.map(item => <li key={item.id} className='things_bg'>
                                    <input type="checkbox" checked={item.checked} onChange={(ev) => { changeCK(item.id, ev) }} />
                                    <div className="picture">
                                        <img src={item.pic} alt={item.pic} />
                                    </div>
                                    <div className='con_right' style={{ width: '160px', height: '100px', }}>
                                        <p className='text' style={{ fontSize: '16px', color: '#474747', fontWeight: '600' }}>{item.name}</p>
                                        <p className='text_2' style={{ fontSize: '20px', color: '#f12525', fontWeight: '600', marginTop: '50px' }}>￥{(item.price * item.num)}</p>
                                        <div style={{ display: 'flex', width: '150px' }}>
                                            <button style={{ width: '30px' }} onClick={() => { delNum(item.id) }}>-</button>
                                            <p style={{ width: '30px', textAlign: 'center' }}>{item.num}</p>
                                            <button style={{ width: '30px' }} onClick={() => { addNum(item.id) }}>+</button>
                                        </div>
                                    </div>
                                </li>)
                            }
                        </ul>
                        <li style={{ position: 'fixed', bottom: '50px', width: '100%', height: '50px', background: '#fff' }}>
                            <input type="checkbox" checked={cart.length && cart.every(v => v.checked)} onChange={(e) => { checkedAll(e) }} />
                            已选：{num}

                            总价：{sum}
                            <button onClick={jiesuanFn}>去结算</button>

                        </li>
                    </div >


            }
        </div>

    )
}
export default connect(state => ({ cart: state.cart }), { editCartAction, incrementNum, decrementNum })(React.memo(Cart))